<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form-model layout="inline" ref="ruleForm" :model="queryParam">
          <z-form-item :datas="fieldArr" :form="queryParam" :submitAction="{show: true, toggle: false, span: 8}" @change="getChangeTime" @onSubmit="onQuery" @onReset="onResetForm">
            <!--//自定义生效范围-->
            <template slot="slots-rangeId">
              <j-select-depart v-model="queryParam.rangeId" :trigger-change="true" :multi="true" @rows="getSelectRows" />
            </template>
          </z-form-item>
        </a-form-model>
      </div>
    </a-card>
    <a-card :bordered="false">
      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <div>
          <a-button type="primary" @click="handleProcess('add')">新增流程</a-button>
        </div>
      </div>
      <!-- 表格展示 -->
      <div class="table-page-content">
        <z-table
          ref="table"
          rowKey="id"
          :showAlert="false"
          :showSelection="false"
          :loading="loading"
          :columns="columns"
          :dataSource="pageData"
          @change="onTableChange"
        />
      </div>
    </a-card>
  </div>
</template>

<script>
import * as flowServiceApi from '@/api/sjsk/flowService'
export default {
  data() {
    return {
      loading: false,
      queryParam: {},
      fieldArr: [
        {label: '流程名称', prop: 'name', tagType: 'input', span: 8},
        {label: '业务类型', prop: 'type', tagType: 'dict-select', dictCode: 'process_approval_type', span: 8},
        {label: '流程状态', prop: 'status', tagType: 'dict-select', dictOptions: [{text: '全部', value: ''}, {text: '使用中', value: '1'},{text: '停用', value: '2'}], span: 8},
        {label: '创建日期', prop: 'createTime', tagType: 'range-picker', format: 'YYYY-MM-DD', span: 8},
        {label: '生效范围', prop: 'rangeId', span: 8},
      ],
      columns: [
        { title: '序号', dataIndex: 'order', width: 60, align: 'center',
          customRender: (text, record, index) =>
            `${(this.pageFilter.pageNo - 1) * this.pageFilter.pageSize +
              (index + 1)}` //序号分页后连续
        },
        { title: '流程名称', dataIndex: 'name', width: 100, align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={10} />
          }
        },
        { title: "业务类型", dataIndex: 'type', width: 100, align: 'center',
          customRender: text => {
            return <j-ellipsis value={this.$filterDictTextByCache('process_approval_type', text)} length={10} />
          }
        },
        { title: '生效范围', dataIndex: 'rangeName', width: 100, align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={10} />
          }
        },
        { title: '创建日期', dataIndex: 'createTime', width: 90, align: 'center' },
        { title: '更新时间', dataIndex: 'updateTime', width: 90, align: 'center' },
        { title: '状态', dataIndex: 'statusName', width: 60, align: 'center',
          customRender: (text, record, index) => {
            return <span class={record.status==1 ? 'text_color_1' : record.status==2 ? 'text_color_2' : ''}> {text} </span>
          }
        },
        {
          title: '操作',
          width: 120,
          align: 'center',
          dataIndex: 'action',
          customRender: (text, record, index) => {
            return (
              <a-space size={0}>
                <a-button onClick={event =>this.handleProcess('details', record)} type='link' style={'padding:0'}>查看</a-button>
                {record.status==2 ? <span>
                  <a-divider type='vertical' style={'margin: 0 6px'}/>
                  <a-button onClick={event =>this.handleProcess('edit', record)} type='link' style={'padding:0'}>编辑</a-button>
                  <a-divider type='vertical' style={'margin: 0 6px'}/>
                  <a-button onClick={event =>this.handleOperate('enable', record)} type='link' style={'padding:0'}>启用</a-button>
                  <a-divider type='vertical' style={'margin: 0 6px'}/>
                  <a-button onClick={event =>this.handleOperate('delete', record)} type='link' style={'padding:0'}>删除</a-button>
                </span> : record.status==1? <span>
                  <a-divider type='vertical' style={'margin: 0 6px'}/>
                  <a-button onClick={event =>this.handleOperate('disable', record)} type='link' style={'padding:0'}>停用</a-button>
                </span> : null}
              </a-space>
            )
          }
        },
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData: {}
    }
  },
  created() {},
  mounted() {
    this.onQuery()
  },
  methods: {
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      // this.$refs.ruleForm.resetFields()
      this.queryParam = {}
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onTableChange(pagination, pageFilter, sorter) {
      this.pageFilter = Object.assign({}, this.pageFilter, pagination);
      this.refreshTable();
    },
    refreshTable() {
      let {createTime, ...dataParam} = this.queryParam // 剔除createTime元素，dataParam最新的对象
      let queryParam = Object.assign({}, dataParam, this.pageFilter)
      this.loading = true
      flowServiceApi.getProcessList(queryParam).then((res) => {
        this.loading = false
        if (res.success) {
          this.pageData = res.result
        }
      }).catch(e=>{
        this.loading = false
        this.$message.warn("请求失败！");
      })
    },
    // 新增流程、编辑流程、查看流程
    handleProcess(type, record) {
      let path
      if (type==='add') {
        path = '/process/add'
      } else if(type==='edit') {
        path = `/process/edit/${record.id}`
      } else if(type==='details') {
        path = `/process/details/${record.id}`
      } 
      this.$router.push({
        path: path
      });
    },
    // 业务操作-启用、停用、删除
    handleOperate(type, record) {
      let that = this
      let title, api, form = {}
      if (type=='enable') {
        title = '启用'
        form = { id: record.id, status: 1 }
      } else if(type=='disable') {
        title = '停用'
        form = { id: record.id, status: 2 }
      } else if(type=='delete') {
        title = '删除'
      }
      this.$confirm({
        title: `确定${title}该流程？`,
        onOk() {
          if (type=='enable' || type=='disable') {
            api = flowServiceApi.operateProcess(form)
          } else if(type=='delete') {
            api = flowServiceApi.deleteProcess(record.id)
          }
          api.then((res) => {
            if (res.success) {
              that.$message.success(res.message? res.message: `${title}操作成功！`)
              that.onQuery()
            } else {
              that.$message.warn(res.message? res.message: `${title}操作失败！`)
            }
          }).catch(e=>{
            that.$message.warn("操作失败！")
          })
        }
      })
    },
    // 生效范围
    getSelectRows(rows) {
      if(rows && rows.length>0) {
        let rangeNames = rows.map(v => v.title).join(',')
        this.$set(this.queryParam, 'rangeName', rangeNames)
      } else {
        this.$set(this.queryParam, 'rangeName', '')
      }
    },
    // 获取组件的时间， prop为对应的字段，date为选中的时间值
    getChangeTime(prop, date) {
      if(prop === 'createTime') {
        this.$set( this.queryParam, 'startTime', date[0] )
        this.$set( this.queryParam, 'endTime', date[1] )
      }
    }
  }
}
</script>
<style lang="less" scoped>
.text_color_1 {
  color: #70B603;
}
.text_color_2 {
  color: #d9001b;
}
</style>
